#!/bin/bash
#Author: nicheng
#Update: 2020-07-20
#Description: The script is used to deploy market website.
#set -euxo pipefail
start=$(date +%s) 
phpconfdir=/www/market/wwwroot
siteconfdir=/www/market/wwwconfig
deploysitedir=/root/nicheng
deploysitefile=/root/nicheng/sitename
deploysitedb=/root/nicheng/sitedb
a=0;b=0
#部署站点的参数格式: /www/market/sourcefiles/PHP7001/    PHP7001    www.aa.com   www.0532ycyg.com
#部署站点的源码包命名格式：www.aa.com.zip或者aa.com.zip
[ -d $deploysitedir ] || mkdir $deploysitedir 2> /dev/null
[ -f $deploysitefile ] || touch $deploysitefile 2> /dev/null
[ -f $deploysitedb ] || touch $deploysitedb 2> /dev/null
sed  -i -e '/^[ ]*$/d' -e 's/^[ ]*//g' -e 's/[ ]*$//g' $deploysitefile
deploysitedbcontent=`cat $deploysitefile |wc -l`
dpfiledcount1=`awk '{print $1}' $deploysitefile |grep -v "^[ ]*$" |wc -l`
dpfiledcount2=`awk '{print $2}' $deploysitefile |grep -v "^[ ]*$" |wc -l`
dpfiledcount3=`awk '{print $3}' $deploysitefile |grep -v "^[ ]*$" |wc -l`
dpfiledcount4=`awk '{print $4}' $deploysitefile |grep -v "^[ ]*$" |wc -l`
if [ $deploysitedbcontent -eq 0 ];then
    echo -e  "\033[43;31m部署站点的文件${deploysitefile}的内容为空,请检查后再重新部署.\033[0m"
    exit 1
fi
if [ $dpfiledcount1 != $dpfiledcount2 -o $dpfiledcount1 != $dpfiledcount3 -o $dpfiledcount1 != $dpfiledcount4 -o $dpfiledcount2 != $dpfiledcount3 -o $dpfiledcount2 != $dpfiledcount4 -o $dpfiledcount3 != $dpfiledcount4 ];then
    echo -e "\033[43;31m部署站点的文件${deploysitefile}中缺少相应的参数,请检查.\033[0m"
    exit 2
fi
while read sourcecodedir version newsite templatesite
do
    newst=${newsite#*.}
    configphpdir=$phpconfdir/$version/$newst
    nginxconf=$siteconfdir/$version/${newst}.conf
    if [ -f $configphpdir/e/config/config.php -o -f $configphpdir/application/config/database.php -o -f $configphpdir/wp-config.php -o -f $configphpdir/data/common.inc.php ];then
        if [ -f $nginxconf ];then
            echo -e "\033[41;34m此站点${newsite}已部署好,请检查\033[0m"
            exit 3
        fi
    fi
    if [ -d $configphpdir ];then
        echo -e "\033[41;34m源代码包解压到的目录${configphpdir}已存在,请检查.\033[0m"
        exit 4
    fi
    parameternub=`awk "/$newsite/" $deploysitefile |wc -l`
    if [ $parameternub -gt 1 ];then
        echo -e "\033[43;31m部署站点的文件${deploysitefile}中的参数${newsite}有重复的,请检查.\033[0m"
        exit 5
    fi
    sitedb=${newsite#*.}
    if [ ! -f $sourcecodedir/${newsite}.zip -a ! -f $sourcecodedir/${sitedb}.zip ];then
        echo -e "\033[43;31m源代码包$sourcecodedir/${newsite}.zip和$sourcecodedir/${sitedb}.zip不存在,请检查.\033[0m"
        exit 6
    fi
    if [ ! -d $phpconfdir/$version -o ! -d $siteconfdir/$version ];then
        echo -e "\033[43;31m部署站点的文件${deploysitefile}中的参数${version}有问题,请检查.\033[0m"
        exit 7
    fi
    newsitecount=$(echo $newsite |egrep  '[a-Z|0-9|-]+\.[a-Z|0-9|-]+\.[a-Z|0-9|-]+' |wc -l) ||true
    if [ x$newsitecount != x1 ];then
        echo  -e "\033[43;31m部署站点的文件${deploysitefile}中的参数${newsite}有问题,请检查.\033[0m"
        exit 8
    fi
    templatest=${templatesite#*.}
    templatesitecount=$(echo $templatesite |egrep  '[a-Z|0-9|-]+\.[a-Z|0-9|-]+\.[a-Z|0-9|-]+' |wc -l) ||true
    if [ x$templatesitecount != x1 -o ! -f $siteconfdir/$version/${templatest}.conf ];then
        echo  -e "\033[43;31m部署站点的文件${deploysitefile}中的参数${templatesite}有问题或者模板文件$siteconfdir/$version/${templatest}.conf不存在,请检查.\033[0m"
        exit 9
    fi
done < $deploysitefile
while read sourcecodedir version newsite templatesite
do
    let a+=1
    configphpdir=$phpconfdir/$version/$newst
    sourcecodebag=$sourcecodedir/${newsite}.zip
    if [ ! -f $sourcecodebag ];then
        sitedb=${newsite#*.}
        sourcecodebag=$sourcecodedir/${sitedb}.zip
    fi
    unzip -tq $sourcecodebag  1>& /dev/null
    if [ $? -ne 0 ];then
        echo -e "\033[43;31m部署的站点的源代码包${sourcecodebag}有问题,请检查后再重新部署此站点${newsite}.\033[0m"
        continue
    fi
    unzip -oq $sourcecodebag -d $configphpdir &
    echo -e "\033[41;34m源代码包${sourcecodebag}正在解压......\033[0m"
done < $deploysitefile
while read sourcecodedir version newsite templatesite
do
    newst=${newsite#*.}
    templatest=${templatesite#*.}
    configphpdir=$phpconfdir/$version/$newst
    nginxconf=$siteconfdir/$version/${newst}.conf
    copysiteconf=$siteconfdir/$version/${templatest}.conf
    sitedb=${newsite#*.}
    sitenamedb=${sitedb%.*}
    newsitecount=$(echo $sitenamedb |egrep '[a-Z|0-9|-]+\.[a-Z|0-9|-]+' |wc -l) ||true
    if [ x$newsitecount == x1 ];then
        sitedb=${sitedb#*.}
        sitenamedb=${sitedb%%.*}
    fi
    until [ `ps -aux |grep "$configphpdir" |grep -v 'grep' |wc -l` -eq 0 ]
    do
        sleep 1
    done
    echo  -e "\033[41;34m源代码包解压到目录${configphpdir}成功.\033[0m"
    until [ -f $configphpdir/e/config/config.php -o -f $configphpdir/application/config/database.php -o -f $configphpdir/wp-config.php -o -f $configphpdir/data/common.inc.php ]
    do
        codedirnumber=`ls ${configphpdir} 2> /dev/null |wc -l`
        if [ x$codedirnumber != x1 ];then
            echo -e "\033[43;31mphp配置文件的目录${configphpdir}下文件有问题,请检查后再重新部署此站点${newsite}.\033[0m"
            break
        fi
        codedir=`ls ${configphpdir}`
        cd ${configphpdir}/${codedir} && mv -bf *  ${configphpdir}
        cd ${configphpdir} && rm -rf $codedir
    done
    if [ -f $configphpdir/e/config/config.php -o -f $configphpdir/application/config/database.php -o -f $configphpdir/wp-config.php -o -f $configphpdir/data/common.inc.php ];then
        echo "$sitedb" > testdb
        sed -i 's/\./_/g' testdb
        sitename=`awk '{print $1}' testdb`
        STNAME=`echo ${sitename} |grep '^[0-9]'` ||true
        [ x$sitename == x$STNAME ] &&  sitename=db_$STNAME
        if [ -f ${configphpdir}/e/config/config.php ];then
            phpconf=${configphpdir}/e/config/config.php
            sed -i -e '/dbserver/s/localhost/rm-j6cadguk11ixykhnr.mysql.rds.aliyuncs.com/' -e '/dbusername/s/root/marketdbopa/' -e "/dbpassword/s|=''|='SDFGiyuy@!#6786IP'|"  -e "/dbname/s/ecms75/$sitename/"  $phpconf  && {
                echo -e "\033[41;34m配置文件${phpconf}修改成功.\033[0m" 
            } || {
                echo -e "\033[43;31m配置文件${phpconf}修改失败,请检查后再重新部署此站点${newsite}.\033[0m"
                continue
            }
        elif [ -f $configphpdir/application/config/database.php ];then
            phpconf=$configphpdir/application/config/database.php
            sed -i -e "s#'hostname' => '.*',#'hostname' => 'rm-j6cadguk11ixykhnr.mysql.rds.aliyuncs.com',#g" -e "s#'username' => '.*',#'username' => 'marketdbopa',#g" -e  "s|'password' => '.*',|'password' => 'SDFGiyuy@!#6786IP',|g" -e "s#'database' => '.*',#'database' => '$sitename',#g" $phpconf && {
                echo -e "\033[41;34m配置文件${phpconf}修改成功.\033[0m" 
            } || {
                echo -e "\033[43;31m配置文件${phpconf}修改失败,请检查后再重新部署此站点${newsite}.\033[0m"
                continue
            }
        elif [ -f $configphpdir/wp-config.php ];then
            phpconf=$configphpdir/wp-config.php
            sed -i -e "s#define( 'DB_HOST', '.*' );#define( 'DB_HOST', 'rm-j6cadguk11ixykhnr.mysql.rds.aliyuncs.com' );#g"  -e "s#define( 'DB_USER', '.*' );#define( 'DB_USER', 'marketdbopa' );#g" -e "s|define( 'DB_PASSWORD', '.*' );|define( 'DB_PASSWORD', 'SDFGiyuy@!#6786IP' );|g" -e "s|define( 'DB_NAME', '.*' );|define( 'DB_NAME', '$sitename' );|g" $phpconf && {
                echo -e "\033[41;34m配置文件${phpconf}修改成功.\033[0m" 
            } || {
                echo -e "\033[43;31m配置文件${phpconf}修改失败,请检查后再重新部署此站点${newsite}.\033[0m"
                continue
            }
        elif [ -f $configphpdir/data/common.inc.php ];then
            phpconf=$configphpdir/data/common.inc.php
            sed -i -e "s#\$cfg_dbhost = '.*';#\$cfg_dbhost = 'rm-j6cadguk11ixykhnr.mysql.rds.aliyuncs.com';#g" -e "s#\$cfg_dbuser = '.*';#\$cfg_dbuser = 'marketdbopa';#g" -e "s|\$cfg_dbpwd = '.*';|\$cfg_dbpwd = 'SDFGiyuy@!#6786IP';|g" -e "s|\$cfg_dbname = '.*';|\$cfg_dbname = '$sitename';|g" $phpconf && {
                echo -e "\033[41;34m配置文件${phpconf}修改成功.\033[0m" 
            } || {
                echo -e "\033[43;31m配置文件${phpconf}修改失败,请检查后再重新部署此站点${newsite}.\033[0m"
                continue
            }
        fi
        sed -i "/$sitename/d" $deploysitedb
        echo  "$sitename" >> $deploysitedb
        chown -R www:www $configphpdir &
        cp -a $copysiteconf $nginxconf && {
            let b+=1
            sed -i "s/$templatesite/$newsite/g" $nginxconf
            sed -i "s/$templatest/$newst/g" $nginxconf
            echo -e "\033[41;34m配置文件${nginxconf}修改成功.\033[0m"
        } || {
            echo -e "\033[43;31m配置文件${nginxconf}修改失败,请检查后再重新部署此站点${newsite}.\033[0m"
        }
    fi
done < $deploysitefile
echo -e "\033[40;32mTotal deployments：${a}个.\033[0m\n\033[41;34mSuccessed：${b}个.\033[0m\n\033[43;31mFailed：$[a-b]个.\033[0m"
end=$(date +%s) 
difference=$(( end - start )) 
echo -e "\033[43;31m部署站点所用的时间：$difference seconds.\033[0m"
echo -e "\033[44;33m最后一定不要忘记在阿里云数据库RDS(香港区域)上创建数据库，部署完后nginx -s reload加载服务，测试能不能访问就OK了!!!!!!\033[0m\n\033[44;33m本地测试命令:\033[0m\n\t\033[44;33mcurl -vL http://localhost/e/index.php -H "Host:www.xinggang5.com"\033[0m\n  \t\033[44;33mcurl -vL http://localhost -H "Host:www.xinggang56.com"\033[0m\n  \t\033[44;33m创建的数据库请在文件${deploysitedb}中查看.\033[0m"
# curl -vL http://localhost/e/index.php -H "Host:www.xinggang5.com"
# curl -vL http://localhost -H "Host:www.xinggang56.com"
